<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-row :gutter="10">
        <a-col :md="20" :sm="24">
          <a-button v-if="hasPerm('PB_Material.Add')" type="primary" icon="plus" @click="hanldleAdd()">新建</a-button>
          <a-button
            v-if="hasPerm('PB_Material.Delete')"
            type="primary"
            icon="minus"
            @click="handleDelete(selectedRowKeys)"
            :disabled="!hasSelected()"
            :loading="loading"
          >删除</a-button
          >
          <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>

          <!-- <a-button
            type="primary"
            v-if="hasPerm('PB_Materials.Print')"
            @click="BatchPrinting(selectedRowKeys)"
            :disabled="!hasSelecteds()"
            :loading="loading"
            >打印</a-button
          > -->
          <!-- <a-radio-group v-model="queryParam.IsBecode" button-style="solid" @change="getDataList">
            <a-radio-button :value="null">全部</a-radio-button>
            <a-radio-button :value="1">使用扫码管理</a-radio-button>
            <a-radio-button :value="0">不使用扫码管理</a-radio-button>
          </a-radio-group> -->
        </a-col>

        <a-button v-if="hasPerm('PB_Materials.Leading')" type="primary" @click="hanldleLeading()">导入物品</a-button>
        <!-- <a-button v-if="hasPerm('PB_Materials.Leading')" type="primary" @click="hanldleError()">查看错误</a-button> -->
      </a-row>
    </div>

    <div class="table-page-search-wrapper" style="margin-bottom: 10px">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <materialType-select
              v-model="MaterialTypeId"
              allowClear
              placeholder="物品类别"
            ></materialType-select>
          </a-col>
          <!-- <a-col :md="4" :sm="24">
            <a-select allowClear v-model="queryParam.IsBecode" :default-value="0" placeholder="是否使用条码管理">
              <a-select-option :value="0">不使用条码管理</a-select-option>
              <a-select-option :value="1">使用条码管理</a-select-option>
            </a-select>
          </a-col> -->
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="Name" @keydown="onKeyDownSearch" placeholder="物品名称/编码" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="Spec" @keydown="onKeyDownSearch" placeholder="物品规格" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin-left: 8px"
              @click="reset()"
            >
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 560 }"
      :columns="columns"
      :rowKey="row => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, columnWidth: '4%' }"
      :bordered="true"
      size="small"
    >
      <template slot="UsageStatus" slot-scope="text">
        <a-tag :color="text ? 'green' : 'red'"> {{ text ? '启用' : '停用' }} </a-tag>
      </template>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a v-if="hasPerm('PB_ProcecureMaterial')" @click="OpenProcecureMainList(record.Id)">关联工艺</a>
          <a-divider type="vertical" /> -->
          <a v-if="hasPerm('PB_Material.Edit')" @click="handleStatus(record.Id, record.UsageStatus)">{{
            record.UsageStatus ? '停用' : '启用'
          }}</a>
          <a-divider v-if="hasPerm('PB_Material.Delete')" type="vertical" />
          <a v-if="hasPerm('PB_Material.Edit')" @click="handleEdit(record)">编辑</a>
          <a-divider v-if="hasPerm('PB_Material.Delete')" type="vertical" />
          <a v-if="hasPerm('PB_Material.Delete')" @click="handleDelete([record.Id])">删除</a>
          <!-- <a-divider v-if="hasPerm('PB_Material.QrCode')" type="vertical" />
          <a v-if="hasPerm('PB_Material.QrCode')" @click="openQrcode(record.QrCode, record.Name)">二维码</a> -->
          <!-- <a-divider v-if="hasPerm('PB_Material.QrCode')" type="vertical" />
          <a v-if="hasPerm('PB_Material.QrCode')" @click="openrowedit(record.Id)">打印</a> -->
        </template>
      </span>
      <template slot="IsBatch" slot-scope="text">
        {{ IsBatch(text) }}
      </template>
      <template slot="dataIndex" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
    </a-table>

    <edit-form ref="editForm" :parentObj="this"></edit-form>
    <!-- <ProcecureMaterial ref="ProcecureMaterial" :parentObj="this"></ProcecureMaterial> -->
    <leading-show
      ref="leadingShow"
      :parentObj="this"
      leading="/PB/PB_Material/Import"
      templet="/PB/PB_Material/ExportToExcel"
    ></leading-show>
    <qr-code-view ref="QrCodeView" :parentObj="this"></qr-code-view>
    <PODetailList ref="podetailList" :parentObj="this"></PODetailList>
    <!-- <ErrorDetail ref="errorDetail" :parentObj="this" /> -->
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import MaterialTypeSelect from '../../../components/PB/MaterialTypeSelect'
import LeadingShow from '../../../components/PB/LeadingShow'
// import ProcecureMaterial from '../PB_ProcecureMaterial/ProcecureMaterialList'
// import QrCodeView from '../../../components/QrCdeo/QrCodeView'
// import PODetailList from './BatchPrinting'
// import ErrorDetail from './ErrorDetail.vue'
const columns = [
  {
    title: '序号',
    align: 'center',
    width: '6%',
    scopedSlots: { customRender: 'dataIndex' }
  },
  { title: '物品类型', dataIndex: 'MaterialTypeName' },
  { title: '物品编码', dataIndex: 'Code', ellipsis: true },
  { title: '物品名称', dataIndex: 'Name' },
  // { title: '物品简称', dataIndex: 'SimpleName'},
  { title: '物品规格', dataIndex: 'Spec' },
  // { title: '工序', dataIndex: 'ProcecureName' ,ellipsis: true},
  // { title: '上限数量', dataIndex: 'Max' },
  // { title: '下限数量', dataIndex: 'Min' },
  // {title:'材质',dataIndex:'Ofmaterial'},
  { title: '仓储单位', dataIndex: 'StorageName' },
  {
    title: '状态',
    dataIndex: 'UsageStatus',
    scopedSlots: { customRender: 'UsageStatus' }
  },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, align: 'center' }
]

export default {
  components: {
    EditForm,
    MaterialTypeSelect,
    LeadingShow
    // ProcecureMaterial,
    // QrCodeView,
    // PODetailList
    // ErrorDetail
  },
  mounted () {
    this.getDataList()
  },
  data () {
    return {
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        defaultCurrent: 1,
        onChange: this.onPageChange.bind(this)
      },
      filters: {},
      sorter: { field: 'Code', order: 'asc' },
      loading: false,
      columns,
      queryParam: [],
      selectedRowKeys: [],
      visible: false,
      pid: '',
      defaultValue: false,
      newold: false,
      newid: '',
      MaterialTypeId: '',
      Name: '',
      Spec: ''
    }
  },
  methods: {
    onKeyDownSearch (e) {
      if (e.keyCode === 13) {
        this.pagination.current = 1
        this.getDataList()
      }
    },
    // hanldleError() {
    //   this.$refs.errorDetail.openForm()
    // },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    IsBatch (text) {
      console.log(text)
      var str = ''
      if (text === 0) {
        str = '否'
      } else if (text === 1) {
        str = '是'
      }
      return str
    },
    reset () {
      this.MaterialTypeId = ''
      this.Name = ''
      this.Spec = ''
      this.getDataList()
    },
    getDataList (e, t) {
      // var ke = ''
      // var name = ''

      // this.selectedRowKeys = []
      // if (this.queryParam.Keyword != undefined) {
      //   // alert(this.queryParam.Keyword)\
      //   name = 'Keyword'
      //   ke = this.queryParam.Keyword
      // }
      // if (this.queryParam.MaterialTypeId != undefined) {
      //   // alert(this.queryParam.Keyword)\
      //   name = 'MaterialTypeId'
      //   ke = this.queryParam.MaterialTypeId
      // }
      // alert(this.queryParam.MaterialTypeId)
      this.queryParam = [{ Condition: 'MaterialTypeId', Keyword: this.MaterialTypeId }, {
        Condition: 'Name',
        Keyword: this.Name
      }, {
        Condition: 'Spec',
        Keyword: this.Spec
      }]
      this.loading = true
      this.$http
        .post('/PB/PB_Material/GetMaterialList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'CreateTime',
          SortType: 'desc',
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    // OpenProcecureMainList(value) {
    //   this.$refs.ProcecureMaterial.openDrawer(value)
    // },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleStatus (Id, status) {
      // this.$confirm({
      //   title: '确定要进行该操作吗?',
      //   onOk: () => {
      //     this.$http
      //       .post('/PB/PB_Material/UpdateMaterialUsageStatus', {
      //         Id,
      //         state: !status
      //       })
      //       .then(res => {
      //         if (res.Success) {
      //           this.getDataList()
      //         } else {
      //           this.$message.error(res.Msg)
      //         }
      //       })
      //   }
      // })
      this.$http
        .post('/PB/PB_Material/UpdateMaterialUsageStatus', {
          Id,
          state: !status
        })
        .then(res => {
          if (res.Success) {
            this.$message.success('修改成功')
            this.getDataList()
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    hanldleAdd () {
      this.$refs.editForm.openForm(null, '新建物品')
    },
    onPageChange (current) {
      this.pagination.current = current
    },
    handleEdit (record) {
      console.log(record)
      this.$refs.editForm.openForm(record.Id, '编辑物品')
    },
    hanldleLeading () {
      this.$refs.leadingShow.openForm(null, '导入物品', '物品')
    },
    handleDelete (ids) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/PB/PB_Material/DeleteData', ids).then(resJson => {
            resolve()

            if (resJson.Success) {
              this.$message.success('操作成功!')

              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    },
    BatchPrinting (ids) {
      if (ids.length === 0) {
        this.$message.warning('请选择要打印物品')
        return
      }
      this.visible = true
      this.newid = ids
      this.$refs.podetailList.openDrawer(this.newid, '打印二维码')
    },
    hasSelecteds () {
      return this.selectedRowKeys.length > 0
    },
    Batchdownload (selectedRowKeys) {
      console.log(selectedRowKeys)
    },
    confirm () {
      this.visible = false
      var newcode = ',N '
      this.$refs.podetailList.openDrawer(this.newid, '打印二维码', newcode)
    },
    openrowedit (id) {
      this.$refs.podetailList.openDrawer(id, '打印物品二维码')
    },
    cancel () {
      this.visible = false
      var oldcode = ',O'
      this.$refs.podetailList.openDrawer(this.newid, '打印二维码', oldcode)
    },
    openDrawer (MaterialId) {
      this.title = '选择工艺'
      this.pid = MaterialId
      this.visible = true
      this.getDataList()
    },
    onDrawerClose () {
      this.visible = false
    },
    openQrcode (id, Name) {
      this.$refs.QrCodeView.openForm(id, Name, '物品二维码')
    }
  }
}
</script>
